//
//  SquarePostsDetailsViewController.m
//  安好
//
//  Created by rlp on 14-11-21.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "SquarePostsDetailsViewController.h"
#import "ImageViewListBox.h"
#import "UserManager.h"
#import "AssociatedWithIViewController.h"
#import "FirendDetailViewController.h"
@interface SquarePostsDetailsViewController (){
    NSMutableArray *myToolBarItems;
    NSMutableArray *myToolBarItemsImages;
    NSMutableArray *myToolBarItemsImages1;
    NSMutableArray *myToolBarItemsNumbers;
    
    //存取图片的url
    NSMutableArray *imageURlArrays;
//    NSMutableArray *halfImageURL;
    NSInteger indeximage;//点击的第几个image
//    UITapGestureRecognizer *tapna1;
    
    
    
    
    CGFloat leftImageViewWith;
}
@property (nonatomic,strong)    UITapGestureRecognizer *tapna1;

@property ( nonatomic,strong)UIToolbar *viewToolsBar;

//键盘
/**
 *  判断是否用户手指滚动
 */
@property (nonatomic, assign) BOOL isUserScrolling;

/**
 *  记录旧的textView contentSize Heigth
 */
@property (nonatomic, assign) CGFloat previousTextViewContentHeight;

/**
 *  记录键盘的高度，为了适配iPad和iPhone
 */
@property (nonatomic, assign) CGFloat keyboardViewHeight;

@property (nonatomic, assign) XHInputViewType textViewInputViewType;

//@property (nonatomic, weak, readwrite) XHMessageTableView *messageTableView;
@property (nonatomic, weak, readwrite) XHMessageInputView *messageInputView;
@property (nonatomic, weak, readwrite) XHShareMenuView *shareMenuView;
@property (nonatomic, weak, readwrite) XHEmotionManagerView *emotionManagerView;
@property (nonatomic, strong, readwrite) XHVoiceRecordHUD *voiceRecordHUD;


@property (nonatomic, strong) UIView *headerContainerView;
@property (nonatomic, strong) UIActivityIndicatorView *loadMoreActivityIndicatorView;

/**
 *  管理本机的摄像和图片库的工具对象
 */
@property (nonatomic, strong) XHPhotographyHelper *photographyHelper;

/**
 *  管理地理位置的工具对象
 */
@property (nonatomic, strong) XHLocationHelper *locationHelper;

/**
 *  管理录音工具对象
 */
@property (nonatomic, strong) XHVoiceRecordHelper *voiceRecordHelper;

/**
 *  判断是不是超出了录音最大时长
 */
@property (nonatomic) BOOL isMaxTimeStop;

#pragma mark - DataSource Change
/**
 *  改变数据源需要的子线程
 *
 *  @param queue 子线程执行完成的回调block
 */
- (void)exChangeMessageDataSourceQueue:(void (^)())queue;

/**
 *  执行块代码在主线程
 *
 *  @param queue 主线程执行完成回调block
 */
- (void)exMainQueue:(void (^)())queue;

#pragma mark - Previte Method
/**
 *  判断是否允许滚动
 *
 *  @return 返回判断结果
 */
- (BOOL)shouldAllowScroll;

#pragma mark - Life Cycle
/**
 *  配置默认参数
 */
- (void)setup;

/**
 *  初始化显示控件
 */
- (void)initilzer;

#pragma mark - RecorderPath Helper Method
/**
 *  获取录音的路径
 *
 *  @return 返回录音的路径
 */
- (NSString *)getRecorderPath;

#pragma mark - UITextView Helper Method
/**
 *  获取某个UITextView对象的content高度
 *
 *  @param textView 被获取的textView对象
 *
 *  @return 返回高度
 */
- (CGFloat)getTextViewContentH:(UITextView *)textView;

#pragma mark - Layout Message Input View Helper Method
/**
 *  动态改变TextView的高度
 *
 *  @param textView 被改变的textView对象
 */
- (void)layoutAndAnimateMessageInputTextView:(UITextView *)textView;

#pragma mark - Scroll Message TableView Helper Method
/**
 *  根据bottom的数值配置消息列表的内部布局变化
 *
 *  @param bottom 底部的空缺高度
 */
- (void)setTableViewInsetsWithBottomValue:(CGFloat)bottom;

/**
 *  根据底部高度获取UIEdgeInsets常量
 *
 *  @param bottom 底部高度
 *
 *  @return 返回UIEdgeInsets常量
 */
- (UIEdgeInsets)tableViewInsetsWithBottomValue:(CGFloat)bottom;

#pragma mark - Message Calculate Cell Height
/**
 *  统一计算Cell的高度方法
 *
 *  @param message   被计算目标消息对象
 *  @param indexPath 被计算目标消息所在的位置
 *
 *  @return 返回计算的高度
 */
- (CGFloat)calculateCellHeightWithMessage:(id <XHMessageModel>)message atIndexPath:(NSIndexPath *)indexPath;

#pragma mark - Message Send helper Method
/**
 *  根据文本开始发送文本消息
 *
 *  @param text 目标文本
 */
//- (void)didSendMessageWithText:(NSString *)text;
/**
 *  根据图片开始发送图片消息
 *
 *  @param photo 目标图片
 */
- (void)didSendMessageWithPhoto:(UIImage *)photo;
/**
 *  根据视频的封面和视频的路径开始发送视频消息
 *
 *  @param videoConverPhoto 目标视频的封面图
 *  @param videoPath        目标视频的路径
 */
- (void)didSendMessageWithVideoConverPhoto:(UIImage *)videoConverPhoto videoPath:(NSString *)videoPath;
/**
 *  根据录音路径开始发送语音消息
 *
 *  @param voicePath        目标语音路径
 *  @param voiceDuration    目标语音时长
 */
- (void)didSendMessageWithVoice:(NSString *)voicePath voiceDuration:(NSString*)voiceDuration;
/**
 *  根据第三方gif表情路径开始发送表情消息
 *
 *  @param emotionPath 目标gif表情路径
 */
- (void)didSendEmotionMessageWithEmotionPath:(NSString *)emotionPath;
/**
 *  根据地理位置信息和地理经纬度开始发送地理位置消息
 *
 *  @param geolcations 目标地理信息
 *  @param location    目标地理经纬度
 */
- (void)didSendGeolocationsMessageWithGeolocaltions:(NSString *)geolcations location:(CLLocation *)location;

#pragma mark - Other Menu View Frame Helper Mehtod
/**
 *  根据显示或隐藏的需求对所有第三方Menu进行管理
 *
 *  @param hide 需求条件
 */
- (void)layoutOtherMenuViewHiden:(BOOL)hide;

#pragma mark - Voice Recording Helper Method
/**
 *  开始录音
 */
- (void)startRecord;
/**
 *  完成录音
 */
- (void)finishRecorded;
/**
 *  想停止录音
 */
- (void)pauseRecord;
/**
 *  继续录音
 */
- (void)resumeRecord;
/**
 *  取消录音
 */
- (void)cancelRecord;







@end

@implementation SquarePostsDetailsViewController

#pragma mark - DataSource Change

- (void)exChangeMessageDataSourceQueue:(void (^)())queue {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), queue);
}

- (void)exMainQueue:(void (^)())queue {
    dispatch_async(dispatch_get_main_queue(), queue);
}







#pragma mark - Propertys



- (UIView *)headerContainerView {
    if (!_headerContainerView) {
        _headerContainerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 44)];
        _headerContainerView.backgroundColor = self.tableView.backgroundColor;
        [_headerContainerView addSubview:self.loadMoreActivityIndicatorView];
    }
    return _headerContainerView;
}
- (UIActivityIndicatorView *)loadMoreActivityIndicatorView {
    if (!_loadMoreActivityIndicatorView) {
        _loadMoreActivityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _loadMoreActivityIndicatorView.center = CGPointMake(CGRectGetWidth(_headerContainerView.bounds) / 2.0, CGRectGetHeight(_headerContainerView.bounds) / 2.0);
    }
    return _loadMoreActivityIndicatorView;
}
- (void)setLoadingMoreMessage:(BOOL)loadingMoreMessage {
    _loadingMoreMessage = loadingMoreMessage;
    if (loadingMoreMessage) {
        [self.loadMoreActivityIndicatorView startAnimating];
    } else {
        [self.loadMoreActivityIndicatorView stopAnimating];
    }
}

- (XHShareMenuView *)shareMenuView {
    if (!_shareMenuView) {
        XHShareMenuView *shareMenuView = [[XHShareMenuView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds), CGRectGetWidth(self.view.bounds), self.keyboardViewHeight)];
        shareMenuView.delegate = self;
        shareMenuView.backgroundColor = [UIColor colorWithWhite:0.961 alpha:1.000];
        shareMenuView.alpha = 0.0;
        [self.view addSubview:shareMenuView];
        _shareMenuView = shareMenuView;
    }
    [self.view bringSubviewToFront:_shareMenuView];
    return _shareMenuView;
}

- (XHEmotionManagerView *)emotionManagerView {
    if (!_emotionManagerView) {
        XHEmotionManagerView *emotionManagerView = [[XHEmotionManagerView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds), CGRectGetWidth(self.view.bounds), self.keyboardViewHeight)];
        emotionManagerView.delegate = self;
        emotionManagerView.dataSource = self;
        emotionManagerView.backgroundColor = [UIColor colorWithWhite:0.961 alpha:1.000];
        emotionManagerView.alpha = 0.0;
        [self.view addSubview:emotionManagerView];
        _emotionManagerView = emotionManagerView;
    }
    [self.view bringSubviewToFront:_emotionManagerView];
    return _emotionManagerView;
}

- (XHVoiceRecordHUD *)voiceRecordHUD {
    if (!_voiceRecordHUD) {
        _voiceRecordHUD = [[XHVoiceRecordHUD alloc] initWithFrame:CGRectMake(0, 0, 140, 140)];
    }
    return _voiceRecordHUD;
}

- (XHPhotographyHelper *)photographyHelper {
    if (!_photographyHelper) {
        _photographyHelper = [[XHPhotographyHelper alloc] init];
    }
    return _photographyHelper;
}

- (XHLocationHelper *)locationHelper {
    if (!_locationHelper) {
        _locationHelper = [[XHLocationHelper alloc] init];
    }
    return _locationHelper;
}

- (XHVoiceRecordHelper *)voiceRecordHelper {
    if (!_voiceRecordHelper) {
        _isMaxTimeStop = NO;
        
        WEAKSELF
        _voiceRecordHelper = [[XHVoiceRecordHelper alloc] init];
        _voiceRecordHelper.maxTimeStopRecorderCompletion = ^{
            //MyNSLog("已经达到最大限制时间了，进入下一步的提示");
            
            // Unselect and unhilight the hold down button, and set isMaxTimeStop to YES.
            UIButton *holdDown = weakSelf.messageInputView.holdDownButton;
            holdDown.selected = NO;
            holdDown.highlighted = NO;
            weakSelf.isMaxTimeStop = YES;
            
            [weakSelf finishRecorded];
        };
        _voiceRecordHelper.peakPowerForChannel = ^(float peakPowerForChannel) {
            weakSelf.voiceRecordHUD.peakPower = peakPowerForChannel;
        };
        _voiceRecordHelper.maxRecordTime = kVoiceRecorderTotalTime;
    }
    return _voiceRecordHelper;
}

#pragma mark - Messages View Controller

- (void)finishSendMessageWithBubbleMessageType:(XHBubbleMessageMediaType)mediaType {
    switch (mediaType) {
        case XHBubbleMessageMediaTypeText: {
            [self.messageInputView.inputTextView setText:nil];
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
                self.messageInputView.inputTextView.enablesReturnKeyAutomatically = NO;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self.messageInputView.inputTextView.enablesReturnKeyAutomatically = YES;
                    [self.messageInputView.inputTextView reloadInputViews];
                });
            }
            break;
        }
        case XHBubbleMessageMediaTypePhoto: {
            break;
        }
        case XHBubbleMessageMediaTypeVideo: {
            break;
        }
        case XHBubbleMessageMediaTypeVoice: {
            break;
        }
        case XHBubbleMessageMediaTypeEmotion: {
            break;
        }
        case XHBubbleMessageMediaTypeLocalPosition: {
            break;
        }
        default:
            break;
    }
}

- (void)setBackgroundColor:(UIColor *)color {
//    self.view.backgroundColor = color;
//    self.tableView.backgroundColor = color;
    
}

- (void)setBackgroundImage:(UIImage *)backgroundImage {
    self.tableView.backgroundView = nil;
    self.tableView.backgroundView = [[UIImageView alloc] initWithImage:backgroundImage];
}

- (void)scrollToBottomAnimated:(BOOL)animated {
    if (![self shouldAllowScroll])
        return;
    
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    
    
    if (rows > 0) {
        if (self.selectCellIndex == -1) {
            //CGRectMake(0, 0, 1, 1)可以直接返回到UITableView的最顶端
            [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
        }else{
            
            if (self.huifuFlag==1) {
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectCellIndex inSection:0]
                                      atScrollPosition:UITableViewScrollPositionTop
                                              animated:animated];
            }else if (self.huifuFlag == 2){
                [UIView animateWithDuration:0.0 animations:^{
                    [self.tableView setContentOffset:CGPointMake(0,tabelCellPoint.y-self.messageInputView.frame.origin.y) animated:YES];
                    self.tableView.bouncesZoom = NO;//scroll is no
                    
                }];
            }

//            [self.tableView setContentOffset:CGPointMake(0,self.messageInputView.frame.origin.y) animated:YES];



        }
    }
}

- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath
              atScrollPosition:(UITableViewScrollPosition)position
                      animated:(BOOL)animated {
    if (![self shouldAllowScroll])
        return;
    
    [self.tableView scrollToRowAtIndexPath:indexPath
                                 atScrollPosition:position
                                         animated:animated];
}

#pragma mark - Previte Method

- (BOOL)shouldAllowScroll {
    if (self.isUserScrolling) {
        if ([self.delegate respondsToSelector:@selector(shouldPreventScrollToBottomWhileUserScrolling)]
            && [self.delegate shouldPreventScrollToBottomWhileUserScrolling]) {
            return NO;
        }
    }
    
    return YES;
}

#pragma mark - Life Cycle

- (void)setup {
    // iPhone or iPad keyboard view height set here.
    self.keyboardViewHeight = (kIsiPad ? 264 : 216);
    _allowsPanToDismissKeyboard = NO;
    _allowsSendVoice = NO;
    _allowsSendMultiMedia = NO;
    _allowsSendFace = NO;
    _leftDiyViewButton = YES;
    _rightDiyViewButton = YES;
    _inputViewStyle = XHMessageInputViewStyleFlat;
    
    self.delegate = self;
//    self.dataSource = self;
}

- (id)init {
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)awakeFromNib {
    [self setup];
}

- (void)initilzer {
    
    
    
    
    
    [self setup];
    
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    // 默认设置用户滚动为NO
    _isUserScrolling = NO;
    
    // 初始化message tableView

    self.tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin-((kScreenWidth == 414)?30*1.2:30)) style:UITableViewStylePlain];
    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];//去掉系统的分割线
    [self.tableView addFooterWithTarget:self action:@selector(tableviewWithData)];
    
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
//    [self.view addSubview:self.tableView];

    

    [self.view addSubview:self.tableView];
    [self.view sendSubviewToBack:self.tableView];
    
    [self tableviewWithData];

    
    // 设置Message TableView 的bottom edg
    CGFloat inputViewHeight = (self.inputViewStyle == XHMessageInputViewStyleFlat) ? 45.0f : 40.0f;
    
    [self setTableViewInsetsWithBottomValue:inputViewHeight];
    
    // 设置整体背景颜色
    [self setBackgroundColor:[UIColor whiteColor]];
    
    // 输入工具条的frame
    
    CGRect inputFrame = CGRectMake(0.0f,
                                   self.view.frame.size.height,
                                   self.view.frame.size.width,
                                   inputViewHeight);
    WEAKSELF
    if (self.allowsPanToDismissKeyboard) {
        // 控制输入工具条的位置块
        void (^AnimationForMessageInputViewAtPoint)(CGPoint point) = ^(CGPoint point) {
            CGRect inputViewFrame = weakSelf.messageInputView.frame;
            CGPoint keyboardOrigin = [weakSelf.view convertPoint:point fromView:nil];
            inputViewFrame.origin.y = keyboardOrigin.y - inputViewFrame.size.height;
            weakSelf.messageInputView.frame = inputViewFrame;
        };
        
        self.tableView.keyboardDidScrollToPoint = ^(CGPoint point) {
            if (weakSelf.textViewInputViewType == XHInputViewTypeText)
                AnimationForMessageInputViewAtPoint(point);
        };
        
        self.tableView.keyboardWillSnapBackToPoint = ^(CGPoint point) {
            if (weakSelf.textViewInputViewType == XHInputViewTypeText)
                AnimationForMessageInputViewAtPoint(point);
        };
        
        self.tableView.keyboardWillBeDismissed = ^() {
            CGRect inputViewFrame = weakSelf.messageInputView.frame;
            inputViewFrame.origin.y = weakSelf.view.bounds.size.height - inputViewFrame.size.height;
            //            inputViewFrame.origin.y = weakSelf.view.bounds.size.height;
            
            weakSelf.messageInputView.frame = inputViewFrame;
        };
    }
    
    
    __block CGFloat weakleftImageViewWith = leftImageViewWith;
    // block回调键盘通知
    self.tableView.keyboardWillChange = ^(CGRect keyboardRect, UIViewAnimationOptions options, double duration, BOOL showKeyborad) {
        if (weakSelf.textViewInputViewType == XHInputViewTypeText) {
           BOOL bl =  [weakSelf.messageInputView.inputTextView.placeHolder hasPrefix:@"回复"]; // TRUE
            
            if (bl) {
              UIImageView *imageView =  (UIImageView *)[weakSelf.messageInputView viewWithTag:3];
                imageView.hidden  = YES;
                
                
                
                weakleftImageViewWith = weakSelf.messageInputView.inputTextView.frame.origin.x- imageView.frame.origin.x;
                CGFloat inputTextViewWith = weakSelf.messageInputView.inputTextView.frame.size.width + weakleftImageViewWith;

                
                weakSelf.messageInputView.inputTextView.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y, inputTextViewWith,  weakSelf.messageInputView.inputTextView.frame.size.height);
                
                
            }else{
                UIImageView *imageView =  (UIImageView *)[weakSelf.messageInputView viewWithTag:3];
                imageView.hidden  = NO;
                
                
                if ( weakSelf.messageInputView.inputTextView.frame.origin.x>8) {
                    
                }else{
                    weakleftImageViewWith = 42;
                    CGFloat inputTextViewWith = weakSelf.messageInputView.inputTextView.frame.size.width - weakleftImageViewWith;
                    
                    
                    weakSelf.messageInputView.inputTextView.frame = CGRectMake(weakSelf.messageInputView.inputTextView.frame.origin.x + weakleftImageViewWith, weakSelf.messageInputView.inputTextView.frame.origin.y, inputTextViewWith,  weakSelf.messageInputView.inputTextView.frame.size.height);
                }

            }
            
            
            [UIView animateWithDuration:duration
                                  delay:0.0
                                options:options
                             animations:^{
                                 CGFloat keyboardY = [weakSelf.view convertRect:keyboardRect fromView:nil].origin.y;
                                 
                                 CGRect inputViewFrame = weakSelf.messageInputView.frame;
                                 CGFloat inputViewFrameY = keyboardY - inputViewFrame.size.height;
                                 
                                 // for ipad modal form presentations
                                 CGFloat messageViewFrameBottom = weakSelf.view.frame.size.height - inputViewFrame.size.height;
                                 if (inputViewFrameY > messageViewFrameBottom)
                                     inputViewFrameY = messageViewFrameBottom;
                                 
                                 weakSelf.messageInputView.frame = CGRectMake(inputViewFrame.origin.x,
                                                                              inputViewFrameY,
                                                                              inputViewFrame.size.width,
                                                                              inputViewFrame.size.height);
                                 
                                 [weakSelf setTableViewInsetsWithBottomValue:weakSelf.view.frame.size.height
                                  - weakSelf.messageInputView.frame.origin.y];//rlp键盘弹出时候 tableView上移高速
                                 if (showKeyborad)
                                     [weakSelf scrollToBottomAnimated:NO];
                             }
                             completion:nil];
        }
    };
    
    self.tableView.keyboardDidChange = ^(BOOL didShowed) {
        
        if ([weakSelf.messageInputView.inputTextView isFirstResponder]) {
            if (didShowed) {
                if (weakSelf.textViewInputViewType == XHInputViewTypeText) {
                    weakSelf.shareMenuView.alpha = 0.0;
                    weakSelf.emotionManagerView.alpha = 0.0;
                }

            }
        }else{
            ////MyNSLog("%f,%f", weakSelf.messageInputView.frame.origin.y,weakSelf.view.frame.size.height);
            if (didShowed) {
                if (weakSelf.textViewInputViewType == XHInputViewTypeText) {
                    weakSelf.messageInputView.frame = inputFrame;
                }
            }
            
            
        }
        if (weakSelf.messageInputView.frame.origin.y==weakSelf.view.frame.size.height) {
            if (weakSelf.tableView ) {
                [weakSelf.tableView removeGestureRecognizer:weakSelf.tapna1];
                weakSelf.tapna1=nil;
                
            }
            
        }else if (weakSelf.messageInputView.frame.origin.y<weakSelf.view.frame.size.height){
            if (!weakSelf.tapna1) {
                weakSelf.tapna1 = [[UITapGestureRecognizer alloc]initWithTarget:weakSelf action:@selector(toTop1)];
                [weakSelf.tableView addGestureRecognizer:weakSelf.tapna1];
            }
            
            
        }
    
    };
    
    self.tableView.keyboardDidHide = ^() {
        [weakSelf.messageInputView.inputTextView resignFirstResponder];
    };
    
    // 初始化输入工具条
    XHMessageInputView *inputView = [[XHMessageInputView alloc] initWithFrame:inputFrame];
    inputView.allowsSendFace = self.allowsSendFace;
    inputView.allowsSendVoice = self.allowsSendVoice;
    inputView.allowsSendMultiMedia = self.allowsSendMultiMedia;
    inputView.leftDiyViewButton = self.leftDiyViewButton;
    inputView.rightDiyViewButton = self.rightDiyViewButton;

    inputView.delegate = self;
    [self.view addSubview:inputView];
    [self.view bringSubviewToFront:inputView];
    
    
    
    _messageInputView = inputView;
    
    
    // 设置手势滑动，默认添加一个bar的高度值
    self.tableView.messageInputBarHeight = CGRectGetHeight(_messageInputView.bounds);
    
    
    
    
    
    [self.imageArr addObject:[UIImage imageNamed:@"咨询_添加照片"]];

    self.imageListBox = [[ImageViewListBox alloc]initWithFrame:CGRectMake(0, 0, self.shareMenuView.frame.size.width, self.shareMenuView.frame.size.height) imageViews:self.imageArr];
    self.imageListBox.delegate=self;
    [self.shareMenuView addSubview:self.imageListBox];
    
    
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置键盘通知或者手势控制键盘消失
    [self.tableView setupPanGestureControlKeyboardHide:self.allowsPanToDismissKeyboard];
    
    // KVO 检查contentSize
    [self.messageInputView.inputTextView addObserver:self
                                          forKeyPath:@"contentSize"
                                             options:NSKeyValueObservingOptionNew
                                             context:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 取消输入框
    [self.messageInputView.inputTextView resignFirstResponder];
    [self setEditing:NO animated:YES];
    
    // remove键盘通知或者手势
    [self.tableView disSetupPanGestureControlKeyboardHide:self.allowsPanToDismissKeyboard];
    
    // remove KVO
    [self.messageInputView.inputTextView removeObserver:self forKeyPath:@"contentSize"];
    [[AFHTTPRequestOperationManager manager].operationQueue cancelAllOperations];
    [self hiddenActionView];

    if (self.pop) {
        [self.pop dismiss];
        
    }
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    if (!self.imageArr) {
        self.imageArr = [[NSMutableArray alloc]initWithCapacity:10];
    }
    self.upid =@"0";
    imageURlArrays = [[NSMutableArray alloc]initWithCapacity:10];
    self.halfImageURL= [[NSMutableArray alloc]initWithCapacity:10];

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectCell:) name:@"SELECTCELL" object:nil];
    
    // Do any additional setup after loading the view from its nib.
    myToolBarItems = [NSMutableArray array];
    myToolBarItemsImages = [NSMutableArray arrayWithObjects:@"帖子底部_未收藏",@"帖子底部_未赞",@"帖子底部_未评论.png",@"帖子底部_已分享", nil];
    myToolBarItemsImages1 = [NSMutableArray arrayWithObjects:@"帖子底部_已收藏",@"帖子底部_已赞",@"帖子底部_已评论.png",@"帖子底部_已分享.png", nil];
    
    self.seeStr = @"false";
    self.pages = 1;
    
    
    
    [self makeNavBarView];
//    self.tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-30-64) style:UITableViewStylePlain];
//    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];//去掉系统的分割线
//    [self.tableView addFooterWithTarget:self action:@selector(tableviewWithData)];
//
//    
//    self.tableView.delegate = self;
//    self.tableView.dataSource = self;
//    [self.view addSubview:self.tableView];
//    [self tableviewWithData];

    
    
    // 初始化消息页面布局
    [self initilzer];
//    [[XHMessageBubbleView appearance] setFont:[UIFont systemFontOfSize:16.0f]];

    
//    UITapGestureRecognizer *tapna = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toTop)];
//    [self.navigationController.navigationBar addGestureRecognizer:tapna];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(redDot) name:@"REDDOT1" object:nil];

    
    
}
-(void)toTop1{
    
    self.messageInputView.inputTextView.text = @"";

    self.isUserScrolling = YES;
    
    UIMenuController *menu = [UIMenuController sharedMenuController];
    if (menu.isMenuVisible) {
        [menu setMenuVisible:NO animated:YES];
    }
    
    if (self.textViewInputViewType != XHInputViewTypeNormal) {
        [self layoutOtherMenuViewHiden:YES];
    }}

-(void)toTop{
//    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
//                           atScrollPosition:UITableViewScrollPositionTop
//                                   animated:YES];
    //CGRectMake(0, 0, 1, 1)可以直接返回到UITableView的最顶端
    [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
    
}
/**
 *  tableView数据加载
 */
-(void)tableviewWithData{
    
    [self hideCustomHud];
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)self.pages] forKey:@"page"];
//    [dict setObject:[self.threadListData tid] forKey:@"tid"];
    [dict setObject:@"DESC" forKey:@"order"];
    [dict setObject:self.seeStr forKey:@"see"];
    
    //    ASC/DESC
    NSString *urlstr = @"";
    if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[AssociatedWithIViewController class]]) {
        urlstr = [NSString stringWithFormat:@"%@%@",kBaseURL,self.noticeData.url];
    }else{
        urlstr = [NSString stringWithFormat:@"%@%@%@/",kBaseURL,THREAD_1,[self.threadListData tid]];
    }
    
    //帖子请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:urlstr parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //MyNSLog("responseObject=%@,%@",responseObject,manager.baseURL);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }else{
            if (self.pages==1) {
                [self.squareDetailsBaseClass.data.post removeAllObjects];
            }
//            if ([SquareDetailsBaseClass modelObjectWithDictionary:responseObject].data.post.count>0) {
//                if (self.pages==1) {
//                    [self.squareDetailsBaseClass.data.post removeAllObjects];
//                }
//            }

            if (self.squareDetailsBaseClass==nil) {

                self.squareDetailsBaseClass = [SquareDetailsBaseClass modelObjectWithDictionary:responseObject];//基类 数据模型
            }else{
                if (self.isReload) {
                    [self.squareDetailsBaseClass.data.post removeAllObjects];
                    self.isReload = NO;
                }
                [self.squareDetailsBaseClass.data.post addObjectsFromArray:[SquareDetailsBaseClass modelObjectWithDictionary:responseObject].data.post];
                self.squareDetailsBaseClass.data.thread =[SquareDetailsBaseClass modelObjectWithDictionary:responseObject].data.thread;
                
            
            }
            [self loadheaderView];
      
            NSArray *jsonDictArr =[[SquareDetailsBaseClass modelObjectWithDictionary:responseObject].data.post isEqual:[NSNull null]]?nil:[SquareDetailsBaseClass modelObjectWithDictionary:responseObject].data.post;
            
            if (jsonDictArr!=nil) {
                self.pages++;
                
                [self.tableView reloadData];
                
            }else{
                if (self.pages>1) {
                    //MyNSLog("下拉无数据");
                }
            }

            
            
        }
        [self hiddenActionView];
        [self.tableView footerEndRefreshing];

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self.tableView footerEndRefreshing];

    }];

}
-(void)loadheaderView{
    
    if (self.tableView.tableHeaderView.subviews.count>0) {
        for (UIView *view in self.tableView.tableHeaderView.subviews) {
            [view removeFromSuperview];
        }
    }
    
    
    UIImageView *headImage = [[UIImageView alloc]initWithFrame:CGRectMake(15, 15, (kScreenWidth == 414)?40*1.2:40, (kScreenWidth == 414)?40*1.2:40)];
//    headImage.image = [UIImage imageNamed:@"默认头像"];
    [headImage setImageURLStr:self.squareDetailsBaseClass.data.thread.avatar placeholder:[UIImage imageNamed:@"默认头像"]];
    headImage.layer.masksToBounds = YES;
    headImage.layer.cornerRadius = 3.0;
    headImage.layer.borderWidth = 0.0;
    
    
    
    UILabel *tagText = [[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth-15-headImage.frame.size.width, headImage.frame.origin.y, -headImage.frame.size.width, 18) text:@"楼主" font:[UIFont systemFontOfSize:DVSWITCH_YEXT_FONT] textColor:[UIColor whiteColor] backgroundColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16] numberOfLines:1 lineSpacing:0];
    tagText.textAlignment = NSTextAlignmentCenter;
    tagText.layer.masksToBounds = YES;
    tagText.layer.cornerRadius = 2.0;
    tagText.layer.borderWidth = 0.0;
    
//    UILabel *tagText=tagTextTamp;
    
    tagText.frame =CGRectMake(kScreenWidth-15-tagText.frame.size.width, tagText.frame.origin.y, tagText.frame.size.width+2*2, tagText.frame.size.height);
    
    
    

    
    UILabel *headerTitle = [[UILabel alloc]initWithFrame:CGRectMake(headImage.frame.origin.x+headImage.frame.size.width+15, headImage.frame.origin.y, kScreenWidth-(headImage.frame.size.width)-15*2-tagText.frame.size.width, 18) text:self.squareDetailsBaseClass.data.thread.author font:[UIFont systemFontOfSize:LABEL_FONT_SIZE_TITLE] textColor:TITLE_ARTICLE_CONTENTFONT_COLOR backgroundColor:[UIColor clearColor] numberOfLines:1 lineSpacing:0];
    
    
    
    
    
    
    
    

    UIImage *timeTag = [UIImage imageNamed:@"广场_时间"];
    UIImageView *timeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(headImage.frame.origin.x+headImage.frame.size.width+15, headImage.frame.origin.y+headImage.frame.size.height-12, ((kScreenWidth == 414)?12*1.2:12), ((kScreenWidth == 414)?12*1.2:12))];
    
    timeImageView.image = timeTag;
    
    
    UILabel *headerTimeText = [[UILabel alloc]initWithFrame:CGRectMake(timeImageView.frame.origin.x+timeImageView.frame.size.width+2, timeImageView.frame.origin.y, timeImageView.frame.origin.x+timeImageView.frame.size.width+2-15*2, ((kScreenWidth == 414)?12*1.2:12)) text:self.squareDetailsBaseClass.data.thread.dateline font:[UIFont systemFontOfSize:LABEL_FONT_SIZE_TIME] textColor:TIME_COLOR backgroundColor:[UIColor clearColor] numberOfLines:1 lineSpacing:0];

    
    
    
    NSString *contentTitleStr=[NSString stringWithFormat:@"%@",self.squareDetailsBaseClass.data.thread.subject];
    UILabel *contentTitle = [[UILabel alloc]initWithFrame:CGRectMake(15,headImage.frame.origin.y+headImage.frame.size.height+10, kScreenWidth-15*2, 18) text:contentTitleStr font:[UIFont systemFontOfSize:LABEL_FONT_SIZE_TITLE] textColor:TITLE_ARTICLE_TEXTFONT_COLOR backgroundColor:[UIColor clearColor] numberOfLines:0 lineSpacing:5];
    CGFloat contentTitleHight = 0;
    if (contentTitle==nil||[contentTitle isEqual:[NSNull null]]||contentTitle.text.length==0) {
        contentTitleHight=0;
    }else{
        contentTitleHight = contentTitle.frame.size.height+5;
    }

    
    
    
    
    NSString *contentStr =[NSString stringWithFormat:@"%@",self.squareDetailsBaseClass.data.thread.message];

    
    UILabel *textLabel = [[UILabel alloc]initWithFrame:CGRectMake(15,(headImage.frame.origin.y+headImage.frame.size.height+15)+(contentTitle.frame.size.height+5),kScreenWidth-15*2,0)  text:contentStr font:[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13] textColor:TITLE_ARTICLE_CONTENTFONT_COLOR backgroundColor:[UIColor clearColor] numberOfLines:0 lineSpacing:5];
    
    // contentStr为你要显示的图文字符串
//    NSString *str = [HtmlString transformString:contentStr];
//    RCLabel*textLabel = [[RCLabel alloc]initWithFrame:CGRectMake(10,(headImage.frame.origin.y+headImage.frame.size.height+15)+(contentTitle.frame.size.height+5),kScreenWidth-10*2,0)];
//    textLabel.delegate =self;
//    textLabel.sizeDelegate = self;
//    [textLabel setFont:[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13]];
//    RCLabelComponentsStructure *componentsDS = [RCLabel extractTextStyle:str];
//    textLabel.componentsAndPlainText = componentsDS;
//    CGSize optimalSize = [textLabel optimumSize:YES];   //计算图文混排后的高度
//    
//    textLabel.frame=CGRectMake(10,textLabel.frame.origin.y,kScreenWidth-10*2, optimalSize.height+5);
//    textLabel.lineBreakMode =NSLineBreakByCharWrapping;
//    textLabel.backgroundColor = [UIColor clearColor];
//    textLabel.textColor =[UIColor orangeColor];
//    
//    textLabel.textColor = TITLE_ARTICLE_CONTENTFONT_COLOR;
    
    CGFloat contentHight = 0;
    if (contentStr==nil||[contentStr isEqual:[NSNull null]]||contentStr.length==0) {
        contentHight=0;
    }else{
        contentHight = textLabel.frame.size.height+10;
    }
    
    
    
    
    NSMutableArray *arrimages = [[NSMutableArray alloc ]initWithArray:self.squareDetailsBaseClass.data.thread.pic];
    
    ImageListView *imageListView = [[ImageListView alloc]initWithFrame:CGRectMake(15,  headImage.frame.origin.y+headImage.frame.size.height+15+contentTitleHight+contentHight, kScreenWidth-15*2, 55) imageViews:arrimages];
    imageListView.delegate = self;
    imageListView.tag = 999999;
    CGFloat imageListViewHight = 0;
    if (imageListView.frame.size.height==0) {
        imageListViewHight=0;
    }else{
       imageListViewHight = imageListView.frame.size.height+10;
    }
    
    
    
    

    
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth,headImage.frame.origin.y+headImage.frame.size.height+15+contentTitleHight+contentHight+imageListViewHight+12)];
    headerView.backgroundColor =[UIColor whiteColor];
    
    UIView *headerBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth, headerView.frame.size.height+10)];
    headerBackView.backgroundColor = [UIColor clearColor];
    
    

   /*
    
    NSArray *buttonImageS =[NSArray arrayWithObjects:[UIImage imageNamed:@"广场_赞"],[UIImage imageNamed:@"广场_评论"], nil];
    NSArray *buttonNumber =[NSArray arrayWithObjects:@"1211",@"6", nil];

    for (int i=0; i<buttonImageS.count; i++) {
        

    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((kScreenWidth/2)*i, headerView.frame.size.height-30,kScreenWidth/2, 30)];
        button.tag = i;
    [button setImage:[buttonImageS objectAtIndex:i] forState:UIControlStateNormal];
    [button setTitle:[buttonNumber objectAtIndex:i] forState:UIControlStateNormal];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)];
    [button setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)];
//    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];

    [button setTitleColor:TIME_COLOR forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_TIME];
        
        button.layer.masksToBounds = YES;
//        button.layer.cornerRadius = 2.0;
        button.layer.borderWidth = 0.5f;
        button.layer.borderColor = [ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16].CGColor;
        
        
    [headerView addSubview:button];
    }
  */
    
    
    [headerView addSubview:headImage];
    [headerView addSubview:headerTitle];
    [headerView addSubview:tagText];
    [headerView addSubview:timeImageView];
    [headerView addSubview:contentTitle];
    [headerView addSubview:headerTimeText];
    [headerView addSubview:textLabel];
    
    [headerView addSubview:imageListView];
    [headerBackView addSubview:headerView];
    headerBackView.backgroundColor =[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    
    /**
     给楼主头像加点击事件
     
     */
    UITapGestureRecognizer *headImageViewtapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headerViewSubheadImageViewClick:)];
    [headImage setUserInteractionEnabled:YES];
    [headImage addGestureRecognizer:headImageViewtapGesture];
    
//    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headerviewClick:)];
//    [headerBackView addGestureRecognizer:tapGesture];
    
    self.tableView.tableHeaderView =headerBackView;
    
    [self.tableView reloadData];
    
    
    
    self.viewToolsBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, kScreenHeight-((kScreenWidth == 414)?30*1.2:30)-64, kScreenWidth, ((kScreenWidth == 414)?30*1.2:30))];

    
    myToolBarItemsNumbers = [NSMutableArray arrayWithObjects:[NSString stringWithFormat:@"%@%@",GAP,self.squareDetailsBaseClass.data.thread.collection],[NSString stringWithFormat:@"%@%@",GAP,self.squareDetailsBaseClass.data.thread.good],[NSString stringWithFormat:@"%@%@",GAP,self.squareDetailsBaseClass.data.thread.replies],[NSString stringWithFormat:@"%@分享",GAP], nil];
    
    
    for (int i=0; i< [myToolBarItemsImages count]; i++) {

        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth/5, ((kScreenWidth == 414)?30*1.2:30))];
        button.tag = i;
        [button addTarget:self action:@selector(toolBarItemClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:[myToolBarItemsNumbers objectAtIndex:i] forState:UIControlStateNormal];
        switch (i) {
            case 0:
            {
                if ([[NSString stringWithFormat:@"%.f",self.squareDetailsBaseClass.data.thread.iscollection] integerValue]==1) {
                    [button setImage:[UIImage imageNamed:[myToolBarItemsImages1 objectAtIndex:i]] forState:UIControlStateNormal];
                    
                }else{
                    [button setImage:[UIImage imageNamed:[myToolBarItemsImages objectAtIndex:i]] forState:UIControlStateNormal];
                    
                }

            }
                break;
            case 1:
            {
                if (self.squareDetailsBaseClass.data.thread.isgood==1) {
                    [button setImage:[UIImage imageNamed:[myToolBarItemsImages1 objectAtIndex:i]] forState:UIControlStateNormal];
                    
                }else{
                    [button setImage:[UIImage imageNamed:[myToolBarItemsImages objectAtIndex:i]] forState:UIControlStateNormal];
                    
                }
                
            }
                break;
            case 2:
            {
                if ([[NSString stringWithFormat:@"%@",self.threadListData.closed]integerValue]==1) {
                    [button setImage:[UIImage imageNamed:[myToolBarItemsImages objectAtIndex:i]] forState:UIControlStateNormal];
                    
                }else{
                    [button setImage:[UIImage imageNamed:[myToolBarItemsImages1 objectAtIndex:i]] forState:UIControlStateNormal];
                    
                }
                
            }
                break;
                
            default:{
             [button setImage:[UIImage imageNamed:[myToolBarItemsImages objectAtIndex:i]] forState:UIControlStateNormal];
            }
                break;
        }
        
        
        
        
        [button setTitleColor:TITLE_ARTICLE_CONTENTFONT_COLOR forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:DVSWITCH_YEXT_FONT];
        UIBarButtonItem *myButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
        //        [button sizeToFit];
        [myToolBarItems addObject:myButtonItem];
        
    }
    
    
    
    [self.viewToolsBar setItems:myToolBarItems animated:YES];
    self.viewToolsBar.tintColor = [ClassMethodsViewController colorWithHexString:TABBAR_BACKGROUNDCOLOR_16];
    [self.view addSubview:self.viewToolsBar];


}
#pragma mark - 设置导航条
-(void)makeNavBarView
{
    self.title = @"帖子";
    //贴图
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClicked:)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    
     if (![[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[AssociatedWithIViewController class]]) {
         UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
         [rightButton setImage:[UIImage imageNamed:@"公用_更多"] forState:UIControlStateNormal];
         [rightButton addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
         UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
         self.navigationItem.rightBarButtonItem = rightBarButtonItem;
         [self redDot];
    }
  
    
    
}

-(void)leftButtonClicked:(UIButton *)sender
{
    [self toTop1];
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -
#pragma mark -- click
-(void)rightButtonClicked:(UIButton *)sender
{
    [self shareCencle];//取消分享

    [self toTop1];

    
    for (UIView *view in [UIApplication sharedApplication].keyWindow.subviews) {
//        if ([view isKindOfClass:[PopoverView class]]) {
//            [UIView animateWithDuration:0.3f animations:^{
//                view.alpha = 0;
//            } completion:^(BOOL finished) {
//                view.hidden = YES;
//                [view removeFromSuperview];
//            }];
//            
//        }
        
        //MyNSLog("view-----%@",view);
    }
    
    
    CGPoint point = CGPointMake(sender.frame.origin.x + sender.frame.size.width/2, 64);
    NSArray *titles = @[@"查看全部", @"只看楼主", @"与我相关",@"投诉"];
    NSArray *images = @[@"广场_全部", @"只看楼主_normal", @"回复我的_normal",@"投诉_normal"];
    NSArray *selectImages = @[@"广场_全部", @"只看楼主_pressed", @"回复我的_pressed",@"投诉_pressed"];

    self.pop = [[PopoverView alloc] initWithPoint:point titles:titles images:images selectImage:selectImages];
    
    __block SquarePostsDetailsViewController *mySelf = self;
    self.pop.selectRowAtIndex = ^(NSInteger index){
        //MyNSLog("select index:%d", index);
        switch (index) {
            case 0:
            {
                if (![mySelf.seeStr isEqualToString:@"flase"]) {
                    mySelf.seeStr=@"flase";
                        mySelf.pages = 1;
                    //[self.squareDetailsBaseClass.data.post removeAllObjects];
                    [mySelf tableviewWithData];

                }
            
            }
                break;
            case 1:
            {
                if (![mySelf.seeStr isEqualToString:@"lz"]) {
                    mySelf.seeStr=@"lz";
                        mySelf.pages = 1;
                    //[self.squareDetailsBaseClass.data.post removeAllObjects];
                    [mySelf tableviewWithData];
                    
                }
                
            }
                break;
            case 2:
            {
                AssociatedWithIViewController *associatedWithIViewController = [[AssociatedWithIViewController alloc]initWithNibName:@"AssociatedWithIViewController" bundle:nil];
                associatedWithIViewController.title = @"与我相关";
                [mySelf.navigationController pushViewController:associatedWithIViewController animated:YES];
                
            }
                break;
            case 3:
            {
                ReportViewController *reportViewController = [[ReportViewController alloc]initWithNibName:@"ReportViewController" bundle:nil];
               reportViewController.objectids = mySelf.squareDetailsBaseClass.data.thread.tid;
                reportViewController.report_type =@"1";
                [mySelf.navigationController pushViewController:reportViewController animated:YES];
                
            }
                break;
                
            default:
                break;
        }
    };
    [self.pop show];
    
    
    for (UIView *view in [UIApplication sharedApplication].keyWindow.subviews) {
        //        if ([view isKindOfClass:[PopoverView class]]) {
        //            [UIView animateWithDuration:0.3f animations:^{
        //                view.alpha = 0;
        //            } completion:^(BOOL finished) {
        //                view.hidden = YES;
        //                [view removeFromSuperview];
        //            }];
        //
        //        }
        
        //MyNSLog("view2-----%@",view);
    }
}
//评论主贴
-(void)pinglun:(NSString *)text{

    
    
    
    
//    platform	平台 ios/android
//    version	版本号
//    post	MCRYPT_3DES（加密方式）,包含下面参数
//    tid	帖子id
//    message	内容
//    pic	图片
    NSMutableString *multString=[[NSMutableString alloc]init];
    if (self.halfImageURL.count>0) {
        for (int i=0; i<self.halfImageURL.count; i++) {
            if (i==0) {
                [multString appendString:[self.halfImageURL objectAtIndex:i]];
            }else
            {
                [multString appendString:[NSString stringWithFormat:@",%@",[self.halfImageURL objectAtIndex:i]]];
            }
        }
    }
    else
    {
        NSString *str=@"";
        multString=[NSMutableString stringWithString:str];
    }
    
    
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    NSDictionary *postDic = @{
                               @"tid":[NSString stringWithFormat:@"%@",self.squareDetailsBaseClass.data.thread.tid],
                               @"message":text,
                               @"pic":multString,
                               };

    NSString * postString = [postDic JSONString];
    NSString * encryptPostString = [ClassMethodsViewController encrypt:postString];
    [dict setObject:encryptPostString forKey:@"post"];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,POST_] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
            
            
        }else{
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
            UIBarButtonItem *button = [self.viewToolsBar.items objectAtIndex:2];
            UIButton *btn= (UIButton *)button.customView;
            self.threadListData.replies=  [NSString stringWithFormat:@" %ld",[self.threadListData.replies integerValue]+1];
            [btn setTitle:[NSString stringWithFormat:@"%@",self.threadListData.replies] forState:UIControlStateNormal];
            
            
            

            
            
            self.messageInputView.inputTextView.text = @"";
            [self.imageArr removeAllObjects];
            for (UIView *view in self.imageListBox.subviews) {
                [view removeFromSuperview];
            }
            [self.imageListBox removeFromSuperview];
            
            [self.halfImageURL removeAllObjects];
            [imageURlArrays removeAllObjects];
            
            
            
            self.isReload = YES;
            self.pages = 1;
            [self tableviewWithData];


            //评论成功后键盘消失
            self.textViewInputViewType = XHInputViewTypeShareMenu;
            [self layoutOtherMenuViewHiden:YES];
  
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self showCustomHudSingleLine:[NSString stringWithFormat:@"请求错误%ld",(long)error.code]];
    }];

}
//回复二楼
-(void)hufuSecondFloor:(NSString *)text{
    
    
    
    
    
//    version	版本号
//    post	MCRYPT_3DES（加密方式）,包含下面参数
//    pid	回复楼层的id
//    upid	回复下面楼层的id
//    message	回复内容
//    recvuid	接收人的uid

    
//    [[self.squareDetailsBaseClass.data.post objectAtIndex:self.selectCellIndex] pid];
    
    
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    NSInteger upidIndex = self.selectCellIndex-1>0?self.selectCellIndex-1:0;
    
    
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    NSDictionary *postDic = @{
                              @"pid":self.pid,
                              @"upid":self.upid,
                              @"message":text,
                              @"recvuid":self.recvuid,
                              };
    
    NSString * postString = [postDic JSONString];
    NSString * encryptPostString = [ClassMethodsViewController encrypt:postString];
    [dict setObject:encryptPostString forKey:@"post"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,POST_QUOTE] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("111%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
            
            
        }else{
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
            UIBarButtonItem *button = [self.viewToolsBar.items objectAtIndex:2];
            UIButton *btn= (UIButton *)button.customView;
            self.threadListData.replies=  [NSString stringWithFormat:@" %ld",[self.threadListData.replies integerValue]+1];
            [btn setTitle:[NSString stringWithFormat:@"%@",self.threadListData.replies] forState:UIControlStateNormal];
            
            
//
//            NSString *time = [DateConversion dataWithSecondToNow:[NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]]];
            SquareDetailsQuote *quareDetailsQuote = [SquareDetailsQuote modelObjectWithDictionary:[responseObject objectForKey:@"data"]];
//            quareDetailsQuote.dateline = time;
//            quareDetailsQuote.message = self.messageInputView.inputTextView.text;
            
            
            
            //
            
            
            
            
            
            //评论数大于当前的二级评论数 就不插入数据不做任何处理  否则插入数据
            if ([[[self.squareDetailsBaseClass.data.post objectAtIndex:self.selectCellIndex] quotecount] integerValue]>[[[self.squareDetailsBaseClass.data.post objectAtIndex:self.selectCellIndex] quote] count]) {


            }else{
//                [[[self.squareDetailsBaseClass.data.post objectAtIndex:self.selectCellIndex] quote]addObject:self.quareDetailsQuote1];
                [[[self.squareDetailsBaseClass.data.post objectAtIndex:self.selectCellIndex] quote]addObject:quareDetailsQuote];
                NSIndexPath *indexPath_1=[NSIndexPath indexPathForRow:self.selectCellIndex inSection:0];
                NSArray *indexArray=[NSArray arrayWithObject:indexPath_1];
                [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
            }
            
            
            self.messageInputView.inputTextView.text = @"";
            [self.imageArr removeAllObjects];
            [self.halfImageURL removeAllObjects];
            [imageURlArrays removeAllObjects];
            
//            self.isReload = YES;
//            self.pages = 1;
//            [self gengduo:self.selectCellIndex];
//            [self tableviewWithData];

            
            
            
            [self.messageInputView.inputTextView resignFirstResponder];
            CGRect inputViewFrame = self.messageInputView.frame;
            inputViewFrame.origin.y = self.view.bounds.size.height;
            self.messageInputView.frame = inputViewFrame;

            
            
        }
        if (!self.tapna1) {
            [self.tableView removeGestureRecognizer:self.tapna1];
            self.tapna1=nil;
        }
        [self hiddenActionView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self showCustomHudSingleLine:[NSString stringWithFormat:@"请求错误%ld",(long)error.code]];
        [self hiddenActionView];
    }];
    
}

//添加取消关注
-(void)guanzhu{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:@"join" forKey:@"action"];
    [dict setObject:self.squareDetailsBaseClass.data.thread.gid forKey:@"gid"];
    
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,GROUP_CHANGEUSERGROUP] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            if ([[responseObject objectForKey:@"msg"] length]>0) {
                [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];

            }else{
                [self showCustomHudSingleLine:@"关注失败"];

            }
        }else{
            
            self.squareDetailsBaseClass.data.thread.iscollect = 1;
            
            if ([[responseObject objectForKey:@"msg"] length]>0) {
                [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
                
            }else{
                [self showCustomHudSingleLine:@"关注成功"];
                
            }
        }
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self showCustomHudSingleLine:@"请检查网络"];

    }];
}
-(IBAction)toolBarItemClick:(id)sender{
    UIButton *butotn = sender;
    NSInteger tags =butotn.tag;
    switch (tags) {
        case 0:
        {
            self.flag = flagCollection;
            [self isLogin];

        }
            break;
        case 1:{
            self.flag = flaggood;
            [self isLogin];
        }
            break;
        case 2:{
            self.huifuFlag = 0;
            self.selectCellIndex = -1;
            self.flag = flagreplies;
            self.messageInputView.inputTextView.placeHolder = [NSString stringWithFormat:@"评论%@:",self.squareDetailsBaseClass.data.thread.author];
//            [self.messageInputView changeleftView:YES];
            [self isLogin];


        }
            break;
        case 3:{
            self.flag = flagShare;
            [self showShareView];
        }
            break;
        default:
            break;
    }
    
}
/**
 *  添加收藏
 */
-(void)addOrDeleteCollectionUrlStr:(NSString *)urlStr{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    
    [dict setObject:@"7" forKey:@"type"];//类型 1：疾病2：医院3：科室4：医生5；药品6新闻:7:话题8：急诊9:常识
    if ([urlStr isEqualToString:COLLECTION_DELETE]) {
        //删除收藏
    }else if ([urlStr isEqualToString:COLLECTION_ADDCOLLECTION]) {
            //添加收藏
    [dict setObject:[NSString stringWithFormat:@"%@",self.squareDetailsBaseClass.data.thread.subject] forKey:@"title"];
    

    }
    
    [dict setObject:[NSString stringWithFormat:@"%@",self.squareDetailsBaseClass.data.thread.tid] forKey:@"objectid"];
    

    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,urlStr] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            if ([[responseObject objectForKey:@"msg"] length]>0) {
                [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
                
            }
            
        }else{
            
            
            if ([urlStr isEqualToString:COLLECTION_DELETE]) {
                //删除收藏
                UIBarButtonItem *button = [self.viewToolsBar.items objectAtIndex:0];
                UIButton *btn= (UIButton *)button.customView;
                [btn setImage:[UIImage imageNamed:[myToolBarItemsImages objectAtIndex:0]] forState:UIControlStateNormal];
                
                self.squareDetailsBaseClass.data.thread.collection= [NSString stringWithFormat:@"%ld",[self.squareDetailsBaseClass.data.thread.collection integerValue]-1];
                [btn setTitle:[NSString stringWithFormat:@"%@%@",GAP,self.squareDetailsBaseClass.data.thread.collection] forState:UIControlStateNormal];
                self.squareDetailsBaseClass.data.thread.iscollection =0;
            }else if ([urlStr isEqualToString:COLLECTION_ADDCOLLECTION]) {
                //添加收藏
                UIBarButtonItem *button = [self.viewToolsBar.items objectAtIndex:0];
                UIButton *btn= (UIButton *)button.customView;
                [btn setImage:[UIImage imageNamed:[myToolBarItemsImages1 objectAtIndex:0]] forState:UIControlStateNormal];
                
                self.squareDetailsBaseClass.data.thread.collection= [NSString stringWithFormat:@"%ld",1+[self.squareDetailsBaseClass.data.thread.collection integerValue]];
                [btn setTitle:[NSString stringWithFormat:@"%@%@",GAP,self.squareDetailsBaseClass.data.thread.collection] forState:UIControlStateNormal];
                self.squareDetailsBaseClass.data.thread.iscollection =1;

            }
           
            if ([[responseObject objectForKey:@"msg"] length]>0) {
                [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
                
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self showCustomHudSingleLine:@"请检查网络"];

    }];

}
/**
 *  添加点赞
 */
-(void)addThreadGood{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:[NSString stringWithFormat:@"%@",self.squareDetailsBaseClass.data.thread.tid] forKey:@"tid"];
    
    
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,THREAD_GOOD] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
            
            
        }else{
            UIBarButtonItem *button = [self.viewToolsBar.items objectAtIndex:1];
            UIButton *btn= (UIButton *)button.customView;
            [btn setImage:[UIImage imageNamed:[myToolBarItemsImages1 objectAtIndex:1]] forState:UIControlStateNormal];
            self.squareDetailsBaseClass.data.thread.good=  [NSString stringWithFormat:@"%ld",[self.squareDetailsBaseClass.data.thread.good integerValue]+1];
            [btn setTitle:[NSString stringWithFormat:@"%@%@",GAP,self.squareDetailsBaseClass.data.thread.good] forState:UIControlStateNormal];
            self.squareDetailsBaseClass.data.thread.isgood =1;

            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
#pragma 实现share方法，通过点击的视图的tag值判断是什么类型的分享
- (void)share:(UITapGestureRecognizer *)shareTap{

    NSString *url =[NSString stringWithFormat:@"http://m.niruoanhao.com/share/thread/%@",self.squareDetailsBaseClass.data.thread.tid];
    NSString *title = self.squareDetailsBaseClass.data.thread.subject;
    NSString *message = self.squareDetailsBaseClass.data.thread.message;

    
    
    
    
    switch (shareTap.view.tag) {
        case 11:{//微信
            
            [self weixinShare:url :title :message :[UIImage imageNamed:@"Icon@2x"]];
        }
            break;
        case 12:{//朋友圈
            [self weixinFriendShare:url :title :message :[UIImage imageNamed:@"Icon@2x"]];

        }
            break;
        case 13:{//短信
            [self showSMSPicker:url :title :message :nil];
        }
            break;
        case 14:{//QQ
            [self qqShare:url :title :message :[UIImage imageNamed:@"Icon@2x"]];

        }
            break;
        case 15:{//QQ空间
            [self qqZoneShare:url :title :message :[UIImage imageNamed:@"Icon@2x"]];

        }
            break;
        case 16:{//新浪微博
            [self sinaWeiboShare:url :title :message :[UIImage imageNamed:@"Icon@2x"]];

        }
            break;
            
        default:
            break;
    }
//    [self shareCencle];//取消分享

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark: UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger  numbers=0;
    if (!self.squareDetailsBaseClass) {
        numbers=0;
    }else{
        numbers=self.squareDetailsBaseClass.data.post.count;
    }
    
    return numbers;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat cellHight = [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
    return cellHight;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellWithIdentifier = @"Cell";
    SquarePostsDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellWithIdentifier];
    if (cell == nil) {
        cell = [[SquarePostsDetailsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellWithIdentifier];
    }
    cell.delegate = self;
    cell.imageListView.delegate = self;
//    cell.imageListView.userInteractionEnabled = YES;
    
    [cell.headImage setImageURLStr:[[self.squareDetailsBaseClass.data.post objectAtIndex:indexPath.row] avatar] placeholder:[UIImage imageNamed:@"默认头像"]];
//    cell.headImage.tag = indexPath.row;
    cell.index = indexPath.row;
    
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    [dict setObject:[[self.squareDetailsBaseClass.data.post objectAtIndex:indexPath.row] avatar]  forKey:@"headImage"];
    [dict setObject:[[self.squareDetailsBaseClass.data.post objectAtIndex:indexPath.row] author]  forKey:@"headerTitle"];

    [dict setObject:[(SquareDetailsPost*)[self.squareDetailsBaseClass.data.post objectAtIndex:indexPath.row] dateline]  forKey:@"headerTimeText"];

    [dict setObject:[[self.squareDetailsBaseClass.data.post objectAtIndex:indexPath.row] message]  forKey:@"contentStr"];
    
    switch (indexPath.row) {
        case 0:
        {
            [dict setObject:@"沙发"  forKey:@"tagText"];

        }
            break;
        case 1:
        {
            [dict setObject:@"板凳"  forKey:@"tagText"];
            
        }
            break;
        case 2:
        {
            [dict setObject:@"地板"  forKey:@"tagText"];
            
        }
            break;
            
        default:{
            [dict setObject:[NSString stringWithFormat:@"F%ld",indexPath.row+1]  forKey:@"tagText"];

        }
            break;
    }
    
    [dict setObject:[[self.squareDetailsBaseClass.data.post objectAtIndex:indexPath.row] quote]  forKey:@"quote"];
    [dict setObject:[[self.squareDetailsBaseClass.data.post objectAtIndex:indexPath.row] pic]  forKey:@"imageListimages"];
//    [dict setObject:[NSArray arrayWithObjects:@"http://image.niruoanhao.com/thread/2014/11/21/1416548860liksS.jpg@1e_580w_412h_1c_0i_1o_90Q_1x.jpg",@"http://image.niruoanhao.com/thread/2014/11/21/1416548860liksS.jpg@1e_580w_412h_1c_0i_1o_90Q_1x.jpg", nil]  forKey:@"imageListimages"];
//    [dict setObject:[NSArray arrayWithObjects:@"223323:@#232332323223",@"23232232332:322332332", nil]  forKey:@"quote"];

   
    [dict setObject:[[self.squareDetailsBaseClass.data.post objectAtIndex:indexPath.row] quotecount]  forKey:@"quotecount"];



    [cell setModelData:dict];
    

//    [cell loadCellData:dict];



    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    

    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //MyNSLog("点击cell%d",indexPath.row);
    //MyNSLog("%@", [self.squareDetailsBaseClass.data.post objectAtIndex:indexPath.row]);
    
    
//    [self.messageInputView changeleftView:NO];
//    XHMessageInputView *inputView = [[XHMessageInputView alloc] initWithFrame:self.messageInputView.frame];
//    
//    inputView.allowsSendFace = self.allowsSendFace;
//    inputView.allowsSendVoice = self.allowsSendVoice;
//    inputView.allowsSendMultiMedia = self.allowsSendMultiMedia;
//    inputView.leftDiyViewButton = NO;
//    inputView.rightDiyViewButton = self.rightDiyViewButton;
//    
//    inputView.delegate = self;
//    [self.view addSubview:inputView];
//    [self.view bringSubviewToFront:inputView];
//    _messageInputView = inputView;
    
    self.huifuFlag = 1;
    self.selectCellIndex = indexPath.row;
    self.flag = flagreplies;

    self.upid =@"0";
    self.recvuid=[NSString stringWithFormat:@"%@",[(SquareDetailsPost*)[self.squareDetailsBaseClass.data.post objectAtIndex:self.selectCellIndex] authorid]];
    self.pid=[NSString stringWithFormat:@"%@",[(SquareDetailsPost*)[self.squareDetailsBaseClass.data.post objectAtIndex:self.selectCellIndex] pid]];
    self.messageInputView.inputTextView.placeHolder = [NSString stringWithFormat:@"回复%@:",[[self.squareDetailsBaseClass.data.post objectAtIndex:indexPath.row] author] ];

    [self isLogin];
    
    
//    [[self.squareDetailsBaseClass.data.post objectAtIndex:indexPath.row] author]  forKey:@"headerTitle"];
    
    
    

}

#pragma mark -
#pragma mark -- ImageViewsDelegate
-(void)imageViewsIndex:(NSInteger)index subImageIndex:(NSInteger)imageIndex{
    //MyNSLog("%ld",(long)index);
    NSMutableArray *arrimages = [[NSMutableArray alloc ]initWithArray:self.squareDetailsBaseClass.data.thread.pic];
    
    ImageListView *imageListView = (ImageListView*)[self.tableView viewWithTag:index];
    
    UIImageView *imageView = (UIImageView *)[imageListView viewWithTag:imageIndex];
    
    if (index==999999) {
        NSInteger count = arrimages.count;
        // 1.封装图片数据
        NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
        for (int i = 0; i<count; i++) {
            // 替换为中等尺寸图片
//            NSString *url = arrimages[i];
            MJPhoto *photo = [[MJPhoto alloc] init];
            NSString *url =nil;
            NSRange range;
            range = [arrimages[i] rangeOfString:@"@"];
            if (range.location != NSNotFound) {
                url = [arrimages[i] substringToIndex:range.location];
            }else{
                url = arrimages[i];
            }
            
            
            
            photo.url = [NSURL URLWithString:url]; // 图片路径
            photo.srcImageView = imageView; // 来源于哪个UIImageView
            [photos addObject:photo];
        }
        
        // 2.显示相册
        MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
        browser.currentPhotoIndex = imageIndex; // 弹出相册时显示的第一张图片是？
        browser.photos = photos; // 设置所有的图片
        [browser show];
        

    }else{

    }
}


#pragma mark -
#pragma mark -- ImageViewListBoxDelegate
-(void)imageViewListIndex:(NSInteger)index subImageIndex:(NSInteger)imageIndex{
    if (imageIndex==self.imageArr.count-1) {
        //MyNSLog("添加照片%ld",(long)imageIndex);
        [self cameraClick:nil];
    }
    
    
}
-(void)imageViewListDeleteIndex:(NSInteger)index subImageIndex:(NSInteger)imageIndex{
    
    indeximage = imageIndex;
    [self dodelete:nil];
    
}
- (IBAction)cameraClick:(id)sender{//相机点击事件
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"照相机", @"图片库",nil];
    alert.tag = 10;
    [alert show];
    
    
}
#pragma mark ImagepickviewcontrollerDelegate 选择图片后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:( NSString *)kUTTypeImage]) {
        [self postImage:info];
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }
}
/**
 *  上传图片
 *
 *  @param dic 图片的信息
 */
- (void)postImage:(NSDictionary *)dic
{
    
    
    
    UIImage *postImage = [dic objectForKey:UIImagePickerControllerEditedImage];
    
    
    
    
    [self showActionView];
    NSData* imageData = UIImageJPEGRepresentation(postImage, 0.5);
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@thread/uploadpic/",kBaseURL] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"george.jpg" mimeType:@"image/jpeg"];
        
    } error:nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [self hiddenActionView];
        if (error) {
            //MyNSLog("Error: %@", error);
        } else {
            //图片上传成功
            NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"1"]) {
                [self.halfImageURL addObject:[[responseObject valueForKey:@"data"] valueForKey:@"pic"]];
                [imageURlArrays addObject:[[responseObject valueForKey:@"data"] valueForKey:@"url"]];
                [self.imageArr insertObject:postImage atIndex:self.imageArr.count-1];
                
               
                [self.imageListBox setImages:self.imageArr];
                
            }else
            {
                
            }
        }
    }];
    [uploadTask resume];}
/**
 *  删除上传的图片
 *
 *  @param sender 点击的当前的button
 */
- (void)dodelete:(UIButton *)sender
{
    
    
    [self showActionView];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    
    
    [dict setObject:[self.halfImageURL objectAtIndex:indeximage] forKey:@"picurl"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,THREAD_DELPIC] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
            
            
        }else{
            
            [self.halfImageURL removeObjectAtIndex:indeximage];
            [imageURlArrays removeObjectAtIndex:indeximage];
            
            [self.imageArr removeObjectAtIndex:indeximage];
            [self.imageListBox setImages:self.imageArr];
            if (self.imageArr.count==1) {
            }
            
        }
        [self hiddenActionView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        
        
        
        
    }];

    
}











-(void)Login{
    switch (self.flag) {
        case flagCollection:
        {
            if ([[NSString stringWithFormat:@"%.f",self.squareDetailsBaseClass.data.thread.iscollection] integerValue]==1) {
                //已经收藏
                [self addOrDeleteCollectionUrlStr:COLLECTION_DELETE];//删除收藏
            }else{
                [self addOrDeleteCollectionUrlStr:COLLECTION_ADDCOLLECTION];//添加收藏
            }
        }
            break;
        case flaggood:
        {
//            if (self.squareDetailsBaseClass.data.thread.isgood == 1) {
//                //已经点赞
//                UIAlertView *guanzhuAlert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"您已经关注" delegate:nil cancelButtonTitle:@"关注" otherButtonTitles:@"放弃", nil];
//                [guanzhuAlert show];
//            }else{
                [self addThreadGood];
//            }
        }
            break;
        case flagreplies:
        {
//            if (self.squareDetailsBaseClass.data.thread.iscollect == 1) {
                //已经关注
//                [self pinglun];
//            }else{
//                
//                
//                UIAlertView *guanzhuAlert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"你没有关注本帖,是否关注" delegate:self cancelButtonTitle:@"关注" otherButtonTitles:@"放弃", nil];
//                [guanzhuAlert show];
//                
//                
//            }
            
//            self.selectCellIndex = 0;

            [self.messageInputView.inputTextView becomeFirstResponder];
            
        }
            break;
        case flagShare:
        {
            
        }
            break;
            
        default:
            break;
    }
    
    

}
#pragma mark -
#pragma mark -- UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    if (alertView.tag==10) {
        
        if (buttonIndex==1) {
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
                pickerImage.delegate=self;
                pickerImage.allowsEditing=YES;
                //pickerImage.mediaTypes              默认是静态图片，指定摄像头获取获取数据类型
                pickerImage.sourceType=UIImagePickerControllerSourceTypeCamera;//指定使用相机
                [self presentViewController:pickerImage animated:YES completion:nil];
            }
            else{
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"没有摄像头或摄像头损坏" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
            }
            
        }
        else if(buttonIndex==2)
        {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
                pickerImage.delegate=self;
                NSArray * array1=[NSArray arrayWithObjects:(NSString *)kUTTypeImage,(NSString*)kUTTypeMovie, nil];
                pickerImage.mediaTypes=array1;
                pickerImage.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
                pickerImage.allowsEditing=YES;
                [self presentViewController:pickerImage animated:YES completion:nil];
            }
            else
            {
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"照片库不存在或已损坏" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
            }
        }

        
    }else{
        switch (buttonIndex) {
            case 0:
            {
                [self guanzhu];
            }
                break;
                
            default:
                break;
        }
    }

}
#pragma mark -
#pragma mark - headerView上的点击事件
/**
 *  点击headerview
 *
 *  @param tapGestureRecognizer <#tapGestureRecognizer description#>
 */
-(void)headerviewClick:(UITapGestureRecognizer *)tapGestureRecognizer{
    //MyNSLog("点击headerView ");
    //MyNSLog("aaa%@", self.squareDetailsBaseClass.data.thread);
    
    

}
/**
 *  点击楼主头像
 *
 *  @param tapGestureRecognizer <#tapGestureRecognizer description#>
 */
-(void)headerViewSubheadImageViewClick:(UITapGestureRecognizer *)tapGestureRecognizer{
    //MyNSLog("点击headerView的头像 需要的数据");
    //MyNSLog("%@", self.squareDetailsBaseClass.data.thread);
    FirendDetailViewController *firendDetailVC = [[FirendDetailViewController alloc] initWithNibName:@"FirendDetailViewController" bundle:nil];
    firendDetailVC.firendId = self.squareDetailsBaseClass.data.thread.authorid;
    [self.navigationController pushViewController:firendDetailVC animated:YES];
}


#pragma mark -
#pragma mark - SelectSquarePostsDetailsTableViewCellDelegate
-(void)squarePostsDetailsTableViewWithImageView:(UIImageView *)headimageView didSelectCellAtIndex:(NSInteger)index{
    
    //MyNSLog("点击cell%d的头像",index);
    //MyNSLog("%@", [self.squareDetailsBaseClass.data.post objectAtIndex:index]);
    
    
    
    FirendDetailViewController *firendDetailVC = [[FirendDetailViewController alloc] initWithNibName:@"FirendDetailViewController" bundle:nil];
    firendDetailVC.firendId = [[self.squareDetailsBaseClass.data.post objectAtIndex:index] authorid];
    [self.navigationController pushViewController:firendDetailVC animated:YES];

}

/**
 *  获取更多回复
 *
 *  @param index <#index description#>
 */
-(void)gengduo:(NSInteger)index{
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:[[self.squareDetailsBaseClass.data.post objectAtIndex:index] pid] forKey:@"pid"];

    
    
    
    
    //帖子请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,POST_MOREQUOTE] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("responseObject=%@,%@",responseObject,manager.baseURL);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }else{
//            [[[self.squareDetailsBaseClass.data.post objectAtIndex:index] quote]removeAllObjects];
            for (int i=0; i<[[responseObject objectForKey:@"data"] count]; i++) {
                
                
                
                [[[self.squareDetailsBaseClass.data.post objectAtIndex:index] quote] addObject:[SquareDetailsQuote modelObjectWithDictionary:[[responseObject objectForKey:@"data"] objectAtIndex:i]]];
            }
            
            NSIndexPath *indexPath_1=[NSIndexPath indexPathForRow:index inSection:0];
            NSArray *indexArray=[NSArray arrayWithObject:indexPath_1];
            [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
//            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]
//                                  atScrollPosition:UITableViewScrollPositionBottom
//                                          animated:YES];
            

            
        }
        [self hiddenActionView];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self showCustomHudSingleLine:[NSString stringWithFormat:@"请求错误%ld",(long)error.code]];

        
    }];
}

#pragma mark -
#pragma mark -  SelectSquarePostsDetailsReplylTableViewCellDelegate 嵌套的tableViewcell的点击
-(void)squarePostsDetailsTableViewWithButton:(UIButton *)button didSelectCellAtIndex:(NSInteger)index{

    
    if ([button.titleLabel.text isEqualToString:@"收起"]) {
        
        for (NSInteger i =[[self.squareDetailsBaseClass.data.post objectAtIndex:index] quote].count-1; i>1; i--) {
            [[[self.squareDetailsBaseClass.data.post objectAtIndex:index] quote] removeObjectAtIndex:i];
        }
        

        
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]
                              atScrollPosition:UITableViewScrollPositionTop
                                      animated:YES];
        NSIndexPath *indexPath_1=[NSIndexPath indexPathForRow:index inSection:0];
        NSArray *indexArray=[NSArray arrayWithObject:indexPath_1];
        [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];

    }else{
    [self gengduo:index];
    }
    
}

-(void)squarePostsDetailsReplylTableViewWithTable:(UITableView *)tableView didSelectCellAtIndex:(NSInteger)index{
    //MyNSLog("点击cell%d 的tableview",index);
    //MyNSLog("%@", [[self.squareDetailsBaseClass.data.post objectAtIndex:index] quote]);
}

-(void)selectCell:(NSNotification*)noti{
//    [self.messageInputView changeleftView:NO];
    

    NSDictionary *dic = [noti userInfo];
    UITableView *tableview = [dic objectForKey:@"tableView"];
    
    //cell的坐标点获取
    CGPoint point = [[dic objectForKey:@"cellPoint"] CGPointValue];
    
    
    
//    UITableViewCell *ta = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[[dic objectForKey:@"index"] integerValue] inSection:0]];
//
//    CGPoint tabelcellPoint1 = [tableview convertPoint:point fromView:ta];
//    //MyNSLog("tabelcellPoint1 = %lf,%lf\n", tabelcellPoint1.x, tabelcellPoint1.y);
//    
//    
//    
//    
//    CGPoint tabelPoint = [ta convertPoint:tabelcellPoint1 fromView:self.tableView];
//    //MyNSLog("tabelPoint = %lf,%lf\n", tabelPoint.x, tabelPoint.y);
    
    
    CGPoint tabelPoint = [tableview convertPoint:point toView:self.tableView];
    //MyNSLog("tabelPoint = %lf,%lf\n", tabelPoint.x, tabelPoint.y);
    
    tabelCellPoint = CGPointMake(tabelPoint.x<0?tabelPoint.x*-1:tabelPoint.x, tabelPoint.y<0?tabelPoint.y*-1:tabelPoint.y);
    //cell的坐标点获取
    
    
    
    
    //MyNSLog("选择的cell %@,table %d",[dic objectForKey:@"index"],tableview.tag);

    
    //MyNSLog("%@", [[[self.squareDetailsBaseClass.data.post objectAtIndex:tableview.tag] quote] objectAtIndex:[[dic objectForKey:@"index"] integerValue]]);
    
    SquareDetailsQuote *squareDetailsQuote = [[[self.squareDetailsBaseClass.data.post objectAtIndex:tableview.tag] quote] objectAtIndex:[[dic objectForKey:@"index"] integerValue]];
    
    
    self.upid =[NSString stringWithFormat:@"%@",squareDetailsQuote.pcid];
    self.recvuid=[NSString stringWithFormat:@"%@",squareDetailsQuote.senduid];
    self.pid=[NSString stringWithFormat:@"%@",squareDetailsQuote.pid];
    self.recvusername = [NSString stringWithFormat:@"%@",squareDetailsQuote.recvusername];
    if (self.selectCellIndex==tableview.tag&&self.selectCellIndexTableCell == [[dic objectForKey:@"index"] integerValue]) {
        
    }else{
    self.messageInputView.inputTextView.text = @"";
    }


    self.messageInputView.inputTextView.placeHolder = [NSString stringWithFormat:@"回复%@:",[squareDetailsQuote sendusername]];
    self.huifuFlag = 2;
    self.selectCellIndex = tableview.tag;
    self.flag = flagreplies;
    [self isLogin];

    
}

#pragma 键盘
#pragma mark - View Rotation

- (BOOL)shouldAutorotate {
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

#pragma mark - RecorderPath Helper Method

- (NSString *)getRecorderPath {
    NSString *recorderPath = nil;
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yy-MMMM-dd";
    recorderPath = [[NSString alloc] initWithFormat:@"%@/Documents/", NSHomeDirectory()];
    //    dateFormatter.dateFormat = @"hh-mm-ss";
    dateFormatter.dateFormat = @"yyyy-MM-dd-hh-mm-ss";
    recorderPath = [recorderPath stringByAppendingFormat:@"%@-MySound.caf", [dateFormatter stringFromDate:now]];
    return recorderPath;
}

#pragma mark - UITextView Helper Method

- (CGFloat)getTextViewContentH:(UITextView *)textView {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        return ceilf([textView sizeThatFits:textView.frame.size].height);
    } else {
        return textView.contentSize.height;
    }
}

#pragma mark - Layout Message Input View Helper Method

- (void)layoutAndAnimateMessageInputTextView:(UITextView *)textView {
    CGFloat maxHeight = [XHMessageInputView maxHeight];
    
    CGFloat contentH = [self getTextViewContentH:textView];
    
    BOOL isShrinking = contentH < self.previousTextViewContentHeight;
    CGFloat changeInHeight = contentH - _previousTextViewContentHeight;
    
    if (!isShrinking && (self.previousTextViewContentHeight == maxHeight || textView.text.length == 0)) {
        changeInHeight = 0;
    }
    else {
        changeInHeight = MIN(changeInHeight, maxHeight - self.previousTextViewContentHeight);
    }
    
    if (changeInHeight != 0.0f) {
        [UIView animateWithDuration:0.25f
                         animations:^{
                             [self setTableViewInsetsWithBottomValue:self.tableView.contentInset.bottom + changeInHeight];
                             
                             [self scrollToBottomAnimated:NO];
                             
                             if (isShrinking) {
                                 if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
                                     self.previousTextViewContentHeight = MIN(contentH, maxHeight);
                                 }
                                 // if shrinking the view, animate text view frame BEFORE input view frame
                                 [self.messageInputView adjustTextViewHeightBy:changeInHeight];
                             }
                             
                             CGRect inputViewFrame = self.messageInputView.frame;
                             self.messageInputView.frame = CGRectMake(0.0f,
                                                                      inputViewFrame.origin.y - changeInHeight,
                                                                      inputViewFrame.size.width,
                                                                      inputViewFrame.size.height + changeInHeight);
                             if (!isShrinking) {
                                 if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
                                     self.previousTextViewContentHeight = MIN(contentH, maxHeight);
                                 }
                                 // growing the view, animate the text view frame AFTER input view frame
                                 [self.messageInputView adjustTextViewHeightBy:changeInHeight];
                             }
                         }
                         completion:^(BOOL finished) {
                         }];
        
        self.previousTextViewContentHeight = MIN(contentH, maxHeight);
    }
    
    // Once we reached the max height, we have to consider the bottom offset for the text view.
    // To make visible the last line, again we have to set the content offset.
    if (self.previousTextViewContentHeight == maxHeight) {
        double delayInSeconds = 0.01;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime,
                       dispatch_get_main_queue(),
                       ^(void) {
                           CGPoint bottomOffset = CGPointMake(0.0f, contentH - textView.bounds.size.height);
                           [textView setContentOffset:bottomOffset animated:YES];
                       });
    }
}

#pragma mark - Scroll Message TableView Helper Method

- (void)setTableViewInsetsWithBottomValue:(CGFloat)bottom {
    UIEdgeInsets insets = [self tableViewInsetsWithBottomValue:bottom];
    self.tableView.contentInset = insets;
    self.tableView.scrollIndicatorInsets = insets;
}

- (UIEdgeInsets)tableViewInsetsWithBottomValue:(CGFloat)bottom {
    UIEdgeInsets insets = UIEdgeInsetsZero;
    
    if ([self respondsToSelector:@selector(topLayoutGuide)]) {
        insets.top = 0;
    }
    
    insets.bottom = 0;
    
    return insets;
}




#pragma mark - Other Menu View Frame Helper Mehtod

- (void)layoutOtherMenuViewHiden:(BOOL)hide {
    [self.messageInputView.inputTextView resignFirstResponder];
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        __block CGRect inputViewFrame = self.messageInputView.frame;
        __block CGRect otherMenuViewFrame;
        
        void (^InputViewAnimation)(BOOL hide) = ^(BOOL hide) {
            //            inputViewFrame.origin.y = (hide ? (CGRectGetHeight(self.view.bounds) - CGRectGetHeight(inputViewFrame)) : (CGRectGetMinY(otherMenuViewFrame) - CGRectGetHeight(inputViewFrame)));
            inputViewFrame.origin.y = (hide ? (CGRectGetHeight(self.view.bounds)) : (CGRectGetMinY(otherMenuViewFrame) - CGRectGetHeight(inputViewFrame)));//rlp键盘隐藏inputview y值
            
            self.messageInputView.frame = inputViewFrame;
        };
        
        void (^EmotionManagerViewAnimation)(BOOL hide) = ^(BOOL hide) {
            otherMenuViewFrame = self.emotionManagerView.frame;
            otherMenuViewFrame.origin.y = (hide ? CGRectGetHeight(self.view.frame) : (CGRectGetHeight(self.view.frame) - CGRectGetHeight(otherMenuViewFrame)));
            self.emotionManagerView.alpha = !hide;
            self.emotionManagerView.frame = otherMenuViewFrame;
        };
        
        void (^ShareMenuViewAnimation)(BOOL hide) = ^(BOOL hide) {
            otherMenuViewFrame = self.shareMenuView.frame;
            otherMenuViewFrame.origin.y = (hide ? CGRectGetHeight(self.view.frame) : (CGRectGetHeight(self.view.frame) - CGRectGetHeight(otherMenuViewFrame)));
            self.shareMenuView.alpha = !hide;
            self.shareMenuView.frame = otherMenuViewFrame;
        };
        
        if (hide) {
            switch (self.textViewInputViewType) {
                case XHInputViewTypeEmotion: {
                    EmotionManagerViewAnimation(hide);
                    break;
                }
                case XHInputViewTypeShareMenu: {
                    ShareMenuViewAnimation(hide);
                    break;
                }
                default:
                    break;
            }
        } else {
            
            // 这里需要注意block的执行顺序，因为otherMenuViewFrame是公用的对象，所以对于被隐藏的Menu的frame的origin的y会是最大值
            switch (self.textViewInputViewType) {
                case XHInputViewTypeEmotion: {
                    // 1、先隐藏和自己无关的View
                    ShareMenuViewAnimation(!hide);
                    // 2、再显示和自己相关的View
                    EmotionManagerViewAnimation(hide);
                    break;
                }
                case XHInputViewTypeShareMenu: {
                    // 1、先隐藏和自己无关的View
                    EmotionManagerViewAnimation(!hide);
                    // 2、再显示和自己相关的View
                    ShareMenuViewAnimation(hide);
                    break;
                }
                default:
                    break;
            }
        }
        
        InputViewAnimation(hide);
        
        [self setTableViewInsetsWithBottomValue:self.view.frame.size.height
         - self.messageInputView.frame.origin.y];
        
        [self scrollToBottomAnimated:NO];
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - Voice Recording Helper Method

- (void)prepareRecordWithCompletion:(XHPrepareRecorderCompletion)completion {
    [self.voiceRecordHelper prepareRecordingWithPath:[self getRecorderPath] prepareRecorderCompletion:completion];
}

- (void)startRecord {
    [self.voiceRecordHUD startRecordingHUDAtView:self.view];
    [self.voiceRecordHelper startRecordingWithStartRecorderCompletion:^{
    }];
}

- (void)finishRecorded {
    WEAKSELF
    [self.voiceRecordHUD stopRecordCompled:^(BOOL fnished) {
        weakSelf.voiceRecordHUD = nil;
    }];
    [self.voiceRecordHelper stopRecordingWithStopRecorderCompletion:^{
        [weakSelf didSendMessageWithVoice:weakSelf.voiceRecordHelper.recordPath voiceDuration:weakSelf.voiceRecordHelper.recordDuration];
    }];
}

- (void)pauseRecord {
    [self.voiceRecordHUD pauseRecord];
}

- (void)resumeRecord {
    [self.voiceRecordHUD resaueRecord];
}

- (void)cancelRecord {
    WEAKSELF
    [self.voiceRecordHUD cancelRecordCompled:^(BOOL fnished) {
        weakSelf.voiceRecordHUD = nil;
    }];
    [self.voiceRecordHelper cancelledDeleteWithCompletion:^{
        
    }];
}

#pragma mark - XHMessageInputView Delegate

- (void)inputTextViewWillBeginEditing:(XHMessageTextView *)messageInputTextView {
    self.textViewInputViewType = XHInputViewTypeText;
}

- (void)inputTextViewDidBeginEditing:(XHMessageTextView *)messageInputTextView {
    if (!self.previousTextViewContentHeight)
        self.previousTextViewContentHeight = [self getTextViewContentH:messageInputTextView];
}

- (void)didChangeSendVoiceAction:(BOOL)changed {
    if (changed) {
        if (self.textViewInputViewType == XHInputViewTypeText)
            return;
        // 在这之前，textViewInputViewType已经不是XHTextViewTextInputType
        [self layoutOtherMenuViewHiden:YES];
    }
}

- (void)didSendTextAction:(NSString *)text {
    //MyNSLog("text : %@", text);

    
    switch (self.huifuFlag) {
        case 0:
        {
//            self.textViewInputViewType = XHInputViewTypeShareMenu;
//            [self layoutOtherMenuViewHiden:YES];
            [self pinglun:text];

        }
            break;
        case 1:
        {
            
            
            NSString *time = [DateConversion dataWithSecondToNow:[NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]]];
            SquareDetailsQuote *quareDetailsQuote = [[SquareDetailsQuote alloc]init];
            quareDetailsQuote.dateline = time;
            quareDetailsQuote.message = text;
            quareDetailsQuote.pid =[[self.squareDetailsBaseClass.data.post objectAtIndex:self.selectCellIndex] pid];
            
//            发送人
          UserModel *userModel = [[UserManager shareInstance] getUserInfo];
            quareDetailsQuote.sendusername = userModel.username;
            quareDetailsQuote.senduid = userModel.uid;

//            接收人
            
            
            
            switch (self.huifuFlag) {
                case 1:
                {
                    
                    SquareDetailsPost *squareDetailsPost = [self.squareDetailsBaseClass.data.post objectAtIndex:self.selectCellIndex];
                    
                    
                    
                    quareDetailsQuote.recvusername = squareDetailsPost.author;
                    quareDetailsQuote.recvuid = squareDetailsPost.authorid;
                    quareDetailsQuote.useip = squareDetailsPost.useip;

                }
                    break;
                case 2:
                {
                    quareDetailsQuote.recvusername = self.recvusername;
                    quareDetailsQuote.recvuid = self.recvuid;
                }
                    break;
                    
                default:
                    break;
            }
            
            quareDetailsQuote.pcid = self.upid;
            
            self.quareDetailsQuote1 =quareDetailsQuote;
            

            [self hufuSecondFloor:text];

        }
            break;
        case 2:
        {
            
            
            NSString *time = [DateConversion dataWithSecondToNow:[NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]]];
            SquareDetailsQuote *quareDetailsQuote = [[SquareDetailsQuote alloc]init];
            quareDetailsQuote.dateline = time;
            quareDetailsQuote.message = text;
            quareDetailsQuote.pid =[[self.squareDetailsBaseClass.data.post objectAtIndex:self.selectCellIndex] pid];
            
            //            发送人
            UserModel *userModel = [[UserManager shareInstance] getUserInfo];
            quareDetailsQuote.sendusername = userModel.username;
            quareDetailsQuote.senduid = userModel.uid;
            
            //            接收人
            
            
            
            switch (self.huifuFlag) {
                case 1:
                {
                    
                    SquareDetailsPost *squareDetailsPost = [self.squareDetailsBaseClass.data.post objectAtIndex:self.selectCellIndex];
                    
                    
                    
                    quareDetailsQuote.recvusername = squareDetailsPost.author;
                    quareDetailsQuote.recvuid = squareDetailsPost.authorid;
                    quareDetailsQuote.useip = squareDetailsPost.useip;
                    
                }
                    break;
                case 2:
                {
                    quareDetailsQuote.recvusername = self.recvusername;
                    quareDetailsQuote.recvuid = self.recvuid;
                }
                    break;
                    
                default:
                    break;
            }
            
            quareDetailsQuote.pcid = self.upid;
            
            self.quareDetailsQuote1 =quareDetailsQuote;
            
            
            [self hufuSecondFloor:text];
        }
            break;
            
        default:
            break;
    }
    
    
    
//    [self.messageInputView.inputTextView resignFirstResponder];
//    CGRect inputViewFrame = self.messageInputView.frame;
//    inputViewFrame.origin.y = self.view.bounds.size.height;
//    self.messageInputView.frame = inputViewFrame;
}

- (void)didSelectedMultipleMediaAction {
    //MyNSLog("didSelectedMultipleMediaAction");
    self.textViewInputViewType = XHInputViewTypeShareMenu;
    [self layoutOtherMenuViewHiden:NO];
    
    
//    NSArray *plugIcons = @[@"咨询_添加照片", @"sharemore_video"];
//    [self.imageListBox setImages:[NSMutableArray arrayWithArray:plugIcons]];

    
}

- (void)didSendFaceAction:(BOOL)sendFace {
    if (sendFace) {
        self.textViewInputViewType = XHInputViewTypeEmotion;
        [self layoutOtherMenuViewHiden:NO];
    } else {
        [self.messageInputView.inputTextView becomeFirstResponder];
    }
}

- (void)prepareRecordingVoiceActionWithCompletion:(BOOL (^)(void))completion {
    //MyNSLog("prepareRecordingWithCompletion");
    [self prepareRecordWithCompletion:completion];
}

- (void)didStartRecordingVoiceAction {
    //MyNSLog("didStartRecordingVoice");
    [self startRecord];
}

- (void)didCancelRecordingVoiceAction {
    //MyNSLog("didCancelRecordingVoice");
    [self cancelRecord];
}

- (void)didFinishRecoingVoiceAction {
    //MyNSLog("didFinishRecoingVoice");
    if (self.isMaxTimeStop == NO) {
        [self finishRecorded];
    } else {
        self.isMaxTimeStop = NO;
    }
}

- (void)didDragOutsideAction {
    //MyNSLog("didDragOutsideAction");
    [self resumeRecord];
}

- (void)didDragInsideAction {
    //MyNSLog("didDragInsideAction");
    [self pauseRecord];
}

#pragma mark - XHShareMenuView Delegate

- (void)didSelecteShareMenuItem:(XHShareMenuItem *)shareMenuItem atIndex:(NSInteger)index {
    //MyNSLog("title : %@   index:%ld", shareMenuItem.title, (long)index);

    
    
    WEAKSELF
    void (^PickerMediaBlock)(UIImage *image, NSDictionary *editingInfo) = ^(UIImage *image, NSDictionary *editingInfo) {
        if (image) {
            [weakSelf didSendMessageWithPhoto:image];
        } else {
            if (!editingInfo)
                return ;
            NSString *mediaType = [editingInfo objectForKey: UIImagePickerControllerMediaType];
            NSString *videoPath;
            NSURL *videoUrl;
            if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
                videoUrl = (NSURL*)[editingInfo objectForKey:UIImagePickerControllerMediaURL];
                videoPath = [videoUrl path];
                
                UIImage *thumbnailImage = [XHMessageVideoConverPhotoFactory videoConverPhotoWithVideoPath:videoPath];
                
                [weakSelf didSendMessageWithVideoConverPhoto:thumbnailImage videoPath:videoPath];
            } else {
                [weakSelf didSendMessageWithPhoto:[editingInfo valueForKey:UIImagePickerControllerOriginalImage]];
            }
        }
    };
    switch (index) {
        case 0: {
            [self.photographyHelper showOnPickerViewControllerSourceType:UIImagePickerControllerSourceTypePhotoLibrary onViewController:self compled:PickerMediaBlock];
            break;
        }
        case 1: {
            [self.photographyHelper showOnPickerViewControllerSourceType:UIImagePickerControllerSourceTypeCamera onViewController:self compled:PickerMediaBlock];
            break;
        }
        case 2: {
            WEAKSELF
            [self.locationHelper getCurrentGeolocationsCompled:^(NSArray *placemarks) {
                CLPlacemark *placemark = [placemarks lastObject];
                if (placemark) {
                    NSDictionary *addressDictionary = placemark.addressDictionary;
                    NSArray *formattedAddressLines = [addressDictionary valueForKey:@"FormattedAddressLines"];
                    NSString *geoLocations = [formattedAddressLines lastObject];
                    if (geoLocations) {
                        [weakSelf didSendGeolocationsMessageWithGeolocaltions:geoLocations location:placemark.location];
                    }
                }
            }];
            break;
        }
        default:
            break;
    }
}

#pragma mark - XHEmotionManagerView Delegate

- (void)didSelecteEmotion:(XHEmotion *)emotion atIndexPath:(NSIndexPath *)indexPath {
    if (emotion.emotionPath) {
        [self didSendEmotionMessageWithEmotionPath:emotion.emotionPath];
    }
}

#pragma mark - XHEmotionManagerView DataSource

- (NSInteger)numberOfEmotionManagers {
    return 0;
}

- (XHEmotionManager *)emotionManagerForColumn:(NSInteger)column {
    return nil;
}

- (NSArray *)emotionManagersAtManager {
    return nil;
}

#pragma mark - UIScrollView Delegate
/*

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([self.delegate respondsToSelector:@selector(shouldLoadMoreMessagesScrollToTop)]) {
        BOOL shouldLoadMoreMessages = [self.delegate shouldLoadMoreMessagesScrollToTop];
        if (shouldLoadMoreMessages) {
            if (scrollView.contentOffset.y >=0 && scrollView.contentOffset.y <= 44) {
                if (!self.loadingMoreMessage) {
                    if ([self.delegate respondsToSelector:@selector(loadMoreMessagesScrollTotop)]) {
                        [self.delegate loadMoreMessagesScrollTotop];
                    }
                }
            }
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.isUserScrolling = YES;
    
    UIMenuController *menu = [UIMenuController sharedMenuController];
    if (menu.isMenuVisible) {
        [menu setMenuVisible:NO animated:YES];
    }
    
    if (self.textViewInputViewType != XHInputViewTypeNormal) {
        [self layoutOtherMenuViewHiden:YES];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    self.isUserScrolling = NO;
}
*/
#pragma mark - XHMessageTableViewController Delegate

- (BOOL)shouldPreventScrollToBottomWhileUserScrolling {
    return YES;
}


#pragma mark - Key-value Observing

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    if (object == self.messageInputView.inputTextView && [keyPath isEqualToString:@"contentSize"]) {
        [self layoutAndAnimateMessageInputTextView:object];
    }
}
-(void)redDot{
    UIButton  *rightButton = (UIButton *)[self.navigationItem.rightBarButtonItem customView];
    if ([[[rightButton imageView] image] isEqual:[UIImage imageNamed:@"公用_更多"]]) {
        
        
        
        if ([[[SystemMessageCenter instance] selectAllNoReadedSecretaryNoticeMessage] count]<=0) {
            for (UIView *view in rightButton.subviews) {
                if ([view isKindOfClass:[UIImageView class]]) {
                    if ([[(UIImageView*)view  image] isEqual:[UIImage imageNamed:@"point2"]]) {
                        [view removeFromSuperview];
                    }
                }
                
            }
        }else{
            
            UIImageView *redDot = [[UIImageView alloc]initWithFrame:CGRectMake(rightButton.frame.size.width-10, 0, 10, 12)];
            redDot.image =[UIImage imageNamed:@"point2"];
            [rightButton addSubview:redDot];
        }
        
    }
}
@end
